import { writable, readable, type Writable } from 'svelte/store';

type AnyType = object | string | number | boolean;

export { writable, readable };

const createWritableMap = () => {
	const writableMap = new Map<string, Writable<AnyType>>();

	return (key: string, initialValue: AnyType) => {
		if (!writableMap.has(key)) {
			writableMap.set(key, writable(initialValue));
		}

		return writableMap.get(key);
	};
};

interface GetWritableType<T = any> {
	(key: string, initialValue: AnyType): Writable<T>;
}

export const getWritable = createWritableMap() as GetWritableType;

export function persistentWritable<T>(
	key: string,
	initialValue: AnyType,
	options: { prefix: string } = { prefix: 'svelte-store:' }
): Writable<T> {
	const storeKey = options.prefix + key; // 使用前缀来避免与其他存储的数据冲突
	// 从 localStorage 中读取数据
	const storedValue = localStorage.getItem(storeKey);
	const data = storedValue ? JSON.parse(storedValue) : initialValue;

	const store = getWritable(key, data) as Writable<T>;

	// 监听数据变化，并保存到 localStorage
	store.subscribe((value) => {
		localStorage.setItem(storeKey, JSON.stringify(value));
	});

	return store;
}
